package com.fouram.web.utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 缓存工具类
 *
 * @author Liup
 *
 */
@Slf4j
public class CacheUtils {

	private static LoadingCache<Object, Object> cache = null;
	// 本地缓存最大个数,默认1000
	private static long maximumSize = 1000;
	// 本地缓存有效时间10m
	private static long expireAfterWriteDuration = 10;
	private static String nullValue = "nullValue";

	static {
		cache = CacheBuilder.newBuilder().maximumSize(maximumSize)
				.expireAfterWrite(expireAfterWriteDuration, TimeUnit.MINUTES).recordStats()
				.build(new CacheLoader<Object, Object>() {
					@Override
					public Object load(Object key) throws Exception {
						return nullValue;
					}
				});
	}

	/**
	 * 添加gava缓存
	 *
	 * @param key
	 * @param value
	 */
	public static void putObject(Object key, Object value) {
		try {
			cache.put(key, value);
		} catch (Exception e) {
			log.error("updateSuccess", e);
		}
	}

	/**
	 * 获取gava缓存
	 *
	 * @param key
	 * @return
	 */
	public static Object getObject(Object key) {
		Object answer = null;
		try {
			answer = cache.get(key);
			if (nullValue.equals(answer)) {
				return null;
			}
		} catch (Exception e) {
			log.error("updateSuccess", e);
		}
		return answer;
	}

	/**
	 * 删除gava缓存
	 *
	 * @param key
	 * @return
	 */
	public static Object removeObject(Object key) {
		Object answer = null;
		try {
			answer = getObject(key);
			cache.invalidate(key);
		} catch (Exception e) {
			log.error("updateSuccess", e);
		}
		return answer;
	}

	/**
	 * 清除所有缓存
	 */
	public static void clear() {
		try {
			cache.invalidateAll();
		} catch (Exception e) {
			log.error("updateSuccess", e);

		}
	}

	/**
	 * 缓存gava缓存大小
	 *
	 * @return
	 */
	public static int getSize() {
		int answer = 0;
		try {
			answer = (int) cache.size();
		} catch (Exception e) {
			log.error("updateSuccess", e);
		}
		return answer;
	}

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws InterruptedException {
		Map<String, String> map = Maps.newHashMap();
		map.put("1", "2");
		CacheUtils.putObject("1", map);
		
		Thread.sleep(10000);
		
		Map<String, String> m = (Map<String, String>) CacheUtils.getObject("1");
		System.out.println(m.get("1"));
	}
}